var express = require("express");

var app = express();

app.use(express.static("static"));

var mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1/todolist");


var task = require("./models/task.js").task

var getData = function(req, res, perform) {
    var page = req.query.page;
    var pageCount = req.query.pageCount;
    var queryObj = {};
    if (perform) {
        queryObj = { perform: perform };
    }
    task.count(queryObj, function(err, docs) {
        console.log(queryObj);
        var length = docs;
        var nowTotalPage = Math.ceil(length / pageCount);
        if (page > nowTotalPage) {
            page = nowTotalPage - 1;
        } else if (page < 0) {
            page = 0;
        }
        if (docs <= 0) {
            res.send({
                status: 0, //操作成功 0
                length: 0,
                totalPage: 1,
                page: 0
            });
        } else {
            var skip = page * pageCount;
            task.find(queryObj, null, { skip: skip, limit: pageCount }, function(err, docs) {
                res.send({
                    status: 0,
                    length: length,
                    totalPage: nowTotalPage,
                    page: page,
                    data: docs
                })
            })

        }
    })
}

app.get("/", function(req, res) {
    res.send("你好啊！")
});

app.get("/getTodolistData", function(req, res) {
    var perform = "未完成";
    getData(req, res, perform);
    // var page = req.query.page;
    // var pageCount = req.query.pageCount;
    // task.find({ perform: "未完成" }, null, null, function(err, docs) {
    //     res.send(docs);
    // })

});
app.get("/finish", function(req, res) {
    var perform = "完成";
    getData(req, res, perform);
    // task.find({ perform: "完成" }, null, null, function(err, docs) {
    //     res.send(docs);
    // })

});
app.get("/del", function(req, res) {
    var id = req.query.id;
    task.remove({ _id: id }, function(err) {
        // task.find({ perform: "未完成" }, null, null, function(err, docs) {
        //     res.send({ data: docs });
        // })
        var perform = "未完成";
        getData(req, res, perform);
    })
})

app.get("/add", function(req, res) {
    var newTasks = req.query.newTasks;
    task.create(newTasks, function(err) {
        task.find({}, null, null, function(err, docs) {
            res.send({ data: docs });
        })
    })
});

app.get("/changePerform", function(req, res) {
    var perform = req.query.perform;
    task.update({ perform: perform }, null, function(err) {
        getData(req, res);
    })
})

app.listen(8888);
console.log("服务正在运行");